package cn.kgc.redis.redis;

import cn.kgc.redis.utils.ApplicationContextUtil;
import org.apache.ibatis.cache.Cache;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @author 课工场
 * @date 2024/8/20
 * @description 将mybatis的二级缓存写入redis    分布式缓存
 */
public class RedisCache implements Cache {


    // 缓存数据的命名空间
    private final String id;

    public RedisCache(String id) {
        System.out.println("redisCache() id = " + id);
        this.id = id;
    }

    @Override
    public String getId() {
        return this.id;
    }

    // 写入缓存的方法
    @Override
    public void putObject(Object key, Object value) {

        RedisTemplate redisTemplate = getRedisTemplate();
        HashOperations hashOperations = redisTemplate.opsForHash();
        hashOperations.put(id,key,value);
    }

    // 获取二级缓存的方法
    @Override
    public Object getObject(Object key) {

        RedisTemplate redisTemplate = getRedisTemplate();
        HashOperations hashOperations = redisTemplate.opsForHash();
        Object o = hashOperations.get(id, key);
        return o;
    }

    @Override
    public Object removeObject(Object key) {
        return null;
    }

    // 清空缓存
    @Override
    public void clear() {

        RedisTemplate redisTemplate = getRedisTemplate();
        redisTemplate.delete(id);
    }

    @Override
    public int getSize() {
        return 0;
    }

    //  获取 redisTemplate对象
    public RedisTemplate getRedisTemplate() {

        RedisTemplate redisTemplate = (RedisTemplate) ApplicationContextUtil.getBean("redisTemplate");
        // 设置redis 中 key 和value的序列化方案
        redisTemplate.setValueSerializer(new StringRedisSerializer());
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        return redisTemplate;
    }

}
